package org.example.wework;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.functions.ExpectedCondition;
import org.example.wework.exception.ExceptionHandler;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;

public class BasePage {

    AppiumDriver driver;
    private WebElement currentElement;

    public BasePage(AppiumDriver driver) {
        this.driver = driver;
    }

    public BasePage() {

    }

    public BasePage find(By by) {

        try {
            currentElement = driver.findElement(by);
        } catch (Exception e) {
            ExceptionHandler.retry += 1;
            if (ExceptionHandler.retry > ExceptionHandler.retryMax) {
                throw e;
            }

            String pageSource = driver.getPageSource();
            ExceptionHandler.getAllExceptionHandler().forEach(exceptionHandler->{
                if (exceptionHandler.isHit(pageSource)){
                    exceptionHandler.handle(driver);
                    find(by);
                }

            });


        }

        return this;
    }

    public BasePage click(By by) {
        try {
            find(by).click();
        } catch (Exception e) {

            ExceptionHandler.retry+=1;
            if (ExceptionHandler.retry>ExceptionHandler.retryMax){
                throw e;
            }

            String pageSource=driver.getPageSource();

            ExceptionHandler.getAllExceptionHandler().forEach(exceptionHandler -> {
                if (exceptionHandler.isHit(pageSource)){
                    exceptionHandler.handle(driver);
                    click(by);
                }
            });
        }
        return this;
    }

    public BasePage click() {
        currentElement.click();
        return this;
    }

    public BasePage sendKeys(By by, String keyword) {
        find(by).sendKeys(keyword);
        return this;
    }

    public BasePage sendKeys(String keyword) {
        currentElement.sendKeys(keyword);
        return this;
    }

    public String getText() {
        return currentElement.getText();
    }

    public void wait(ExpectedCondition expectedCondition, int timeout) {
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeout));
        wait.until(expectedCondition);
    }

    public void wait(ExpectedCondition expectedCondition) {
        wait(expectedCondition, 60);
    }
}
